;
"use strict";
!function(win){
	var DRAGOBJ = {
		selectId:'',
	containerIndex: [-1],
	contorlCache: [],
	maxLevel:5,
	idIndex:0,
	dragClass:"can-drag",
	wrapClass:"wrap-widget",
	wrapRoot:"form.can-drag",
	control:null, //中部控件点击后记录控件信息
	objectIndex:-1, //中部控件正在操作的id
	object: {}, //中部控件 用于内容编辑获取编辑的控件
	indexs:{}, //[paren_id, node_index]
	node:{},
	typeObj:{
		id:'',
		name:'',
		type:'',
		value:{},
		is_container:false,
		childs:[],		
		level:0,		
	},
	oldToData:function(obj){
		var is_old_data = this.isOldData(obj);
		if(is_old_data){
			obj['datas']["id"] = obj['datas']["id"]["value"];
			obj['datas']["name"] = obj["name"];
			var typeName = obj['type'];
			obj['type'] = typeName.replace('Widget', '');
			var childs = new Array();
			if(!empty(obj['datas']["value"]['childs'])){
				for(var x of obj['datas']["value"]['childs']){
					childs.push(this.oldToData(x));
				}
			}
			obj['datas']['childs'] = childs;
			obj['datas']["value"] = obj['datas']["value"]["value"];
		}
		return obj;
	},
	moduleToData:function(typec){
		var typeObjec = {
			id: typec.datas['id'],
			name: typec['name'],
			type: typec['type'],
			value: typec['datas']['value'],
			is_container: typec['datas']['is_container'] ? typec['datas']['is_container'] : false,
			childs: typec['datas']['childs'],
			level: typec['datas']['level'] ? typec['datas']['level'] : 0
		};
		return typeObjec;
	},
	dataToModule:function(data){
		var moduleId = MyModules.get(data['type']);
		let typec = deepClone(moduleId);
		if(typec){
			var type = data['type'];
			typec['type'] = type;
			typec.datas['id'] = data['id'];
			typec.datas['value'] = data['datas']['value'];
			typec.datas['childs'] = data['datas']['childs'];
			typec.datas['is_container'] = data['datas']['is_container'];
			typec.datas['level'] = data['datas']['level'];
			return typec;
		}
		return false;
	},
	ldgDefaultBtns:{
		//默认按钮  移动和删除
		move: { class: 'glyphicon glyphicon-move controlMove' },
		edit: { class: 'glyphicon glyphicon-edit controlEdit' },
		delete: { class: 'glyphicon glyphicon-trash controlDelete' },
	},
	// 菜单移动初始化
	initControl: function(type, value){
		var moduleId = MyModules.get(type);
		let typec = this.toControl(type, value);
		if(typec){
			this.control = typec;
			this.containerIndex = [-1];
			return typec;
		}
		return false;
	},
	initFormOldData:function(jsonData){
		for(var x in jsonData){
			var model = this.objToControl(jsonData[x]);
			this.addControlObject(model);
		}
	},
	//xml数据初始化
	initFormXml:function(xmlString){
		this.setData(xmlString);
		this.initXmlRender();
	},
	initXmlRender:function(){
		var that = this;
		var selector = that.node.getElementsByTagName('root')[0];
		var wrapRoot = $("form."+that.dragClass);
		wrapRoot.children().remove();
		for(var x=0; x< selector.childNodes.length; x++){
			var contorl = selector.childNodes[x];
			var shtml = that.nodeToHtml(contorl);
			wrapRoot.append(shtml);
		}
	},
	toControl:function(type, value){
		var moduleId = MyModules.get(type);
		let typec = deepClone(moduleId);
		if(typec){
			typec.datas['id'] = type + '_' + Math.round(new Date().getTime())+'_'+this.idIndex;
			this.idIndex = this.idIndex + 1;
			typec.datas['type'] = type;
			typec.init();
			if (value != null) {
				typec.setData(value);
			}			
			typec['type'] = type;
			return typec;
		}
		return false;
	},
	// 编辑区内容移动初始化
	initControlById:function(id){
		console.log(id);
		this.control = this.getContorl(id);
		if(this.control.type=='container'){
			var parent = this.getParentContorlSub(id);

		}
		this.removeContorlNode(id);
	},
	// 删除数据节点
	removeContorlNode:function(id){
		var that = this;
		that.node.getElementById(id).remove();
		return false;
	},
	controlDo:function(previewel){
		if(this.control){
			this.addControlObject(this.control, previewel);
		}
	},
	getFormArea:function(){
		var LdgFormSubjectForm = $('.LdgFormSubject'),
		hr_hegiht = $(".LdgFormSubject > .LdgFormButton").eq(0).outerHeight(true);
		formLeft = LdgFormSubjectForm.offset().left;
		formTop = LdgFormSubjectForm.offset().top;
		formRight = formLeft + LdgFormSubjectForm.width();
		formBottom = formTop + LdgFormSubjectForm.height();
		return {
			left:formLeft,
			top:formTop,
			right:formRight,
			bottom:formBottom,
		};
	},
	getData:function(){
		// return this.contorlCache;
		var serializer = new XMLSerializer();
		var xmlString = serializer.serializeToString(this.node);
		return xmlString;
	},
	setData:function(xmlString){
		var parser = new DOMParser();
		var xmlDoc = parser.parseFromString(xmlString, "text/xml");
		this.node = xmlDoc;
	},
	dragOff:function(obj){
		$('.dragControl').empty();
		this.cleanPositionClass();
		this.control = null;
	},
	clear:function() {
		$('.LdgFormSubjectForm').html('');
		this.contorlCache = [];
		this.indexs = {};
		xmlDoc = document.implementation.createDocument(null, null, null);
		root = xmlDoc.createElement("root");
		xmlDoc.appendChild(root);
		this.node = xmlDoc;
		$('.dragControl').empty();
		this.cleanPositionClass();
		this.control = null;
	},
	cleanPositionClass:function(){
		$('.main-container').find(".placeLocationBottom").removeClass("placeLocationBottom");
		$('.main-container').find(".placeLocationTop").removeClass("placeLocationTop");
		$('.main-container').find(".placeLocationInner").removeClass("placeLocationInner");
		$('.main-container').removeClass("placeLocationTop");
		$('.main-container').removeClass("placeLocationBottom");		
	}
}
var xmlDoc = document.implementation.createDocument(null, null, null);
var root = xmlDoc.createElement("root");
xmlDoc.appendChild(root);
DRAGOBJ.node = xmlDoc;

DRAGOBJ.GetBtns = function(btns, id, title) {
	var that = this;
    let str = '<!--表单控件的功能按钮-->';
    str += '<div class="LdgFormItemGroupButton">';
    if (btns) {
        for (let key in btns) {
            str += '<i  class="' + btns[key].class + '"></i>';
        }
    } else {
        for (let key in that.ldgDefaultBtns) {
            str += '<i  class="' + that.ldgDefaultBtns[key].class + '"></i>';
        }
    }
    str += '<span class="LdgFormItemID">' + id + '</span>';
    if(title){
    	str += '<span class="btn btn-default btn-xs">' + title + '</span>';
    }
    str += '</div>';
    return str
}
DRAGOBJ.switchType = function(typeinfo, type,isdiy) {
	var that = this;
    if ('undefined' != typeof typeinfo.getHtml) {
        return typeinfo.getHtml();
    }
    return '';
}
// object轉 modules
DRAGOBJ.objToControl = function(obj){
	var that = this;
	if(typeof obj == 'undefined') return null;
	obj = that.oldToData(obj);
	console.log(obj['type']);
	let typec = this.toControl(obj['type'], obj['datas']['value']);
	if(typec){
		if(typeof obj['datas']['childs'] != 'undefined'){
			for(var i=0; i<obj['datas']['childs'].length; i++){
				var new_Arr = []
				for (var j = 0; j < obj['datas']['childs'][i].length; j++) {
					var childObj = that.objToControl(obj['datas']['childs'][i][j]);
					
					new_Arr.push(childObj);
				}
				obj['datas']['childs'][i] = new_Arr;
			}
		}
		// typec.setDatas(obj['datas']);
		return typec;
	}
	return null;
}
DRAGOBJ.addControlObject = function(typec, previewel){
	if(!typec) return false;
	var that = this;
	let isdiyform=false
	if (typeof(previewel)=="undefined" || previewel==""){previewel='.LdgFormSubjectForm';isdiyform=true}

	that.renderControl(typec, $("form."+that.dragClass), that.containerIndex, 0);
	var widget = $("form").find('[data-id="'+typec.datas['id']+'"]').eq(0);
	that.indexs['parent'] = widget.parent().attr("web-drag") ? 'root' : widget.parents("."+that.wrapClass).eq(0).data("id");
	that.indexs['index'] = widget.parent().attr("web-drag") ? widget.parent().index() : widget.index();
	var new_node = that.addToNode(that.node, that.indexs, typec, 0);
	if(typeof(typec.datas['target'])!="undefined" && typec.datas['target']=='container'){
		var selector = new_node.getElementById(typec.datas['id']);
		if(selector.childNodes.length==0){
			for(var x =0; x<typec.datas.childs[0];x++){
				var container = that.toControl('container');
				var indexs = {parent:typec.datas['id'], index:x};
				that.renderNode(container, indexs);
				new_node = that.addToNode(new_node, indexs, container, 0);
			}
		}
	}
	that.node = new_node;
	containerIndex = [-1]
	that.containerIndex = containerIndex;
}
DRAGOBJ.renderNode = function(typec, indexs){
	var that = this;
	var selector = $("form."+that.dragClass).find("[data-id='"+indexs["parent"]+"']");
	var childNode = selector.children().eq(indexs['index']);
	var str = that.switchType(typec, typec['type']);
	if(childNode.length>0){
		childNode.before(str);
	}else{
		selector.append(str);
	}
}
DRAGOBJ.renderControl = function(control, node, ids, level){ //node 父级节点
	var that = this;
	var	id = ids[level];
	var str = that.switchType(control, control['type']);
	
	str = ids.length==1 ? "<section class='row container-row' web-drag='wrap'>"+str+"</section>" : str;
	if(ids.length == 1){
		if(id==-1){
			$(node).append(str);
		}else if(id==-2){
			$(node).children().eq(0).before(str);
		}else{
			$(node).children().eq(id).after(str);
		}
	}else if(level == ids.length-1 || level == that.maxLevel){
		var index = ids[level];
		if(id==-1){
			$(node).append(str);
		}else{
			if($(node).hasClass(that.wrapClass) && $(node).children("."+that.dragClass).length>0){
				$(node).children().eq(index).append(str);
			}else if($(node).hasClass(that.wrapClass) && !$(node).hasClass(that.dragClass)){
				$(node).eq(index).append(str);
			}else if($(node).hasClass(that.dragClass)){
				$(node).children().eq(index).after(str);
			}else if($(node).children().eq(index).length>0){
				$(node).children().eq(index).after(str);
			}else if($(node).eq(index).length>0){
				$(node).eq(index).after(str);
			}else{
				$(node).append(str);
			}
		}
	}else{
		if(!empty($(node).children().eq(id).attr("web-drag"))){//第一级
			//$(node).children().eq(id) form child index = id 的所有子节点
			var childNode = $(node).children().eq(id).children();
			level = level+1;
		}else if($(node).hasClass(that.wrapClass) && $(node).children("."+that.dragClass).length > 0){
			//当有 can drap容器时 放在can drap容器对应节点
			var childNode = $(node).children().eq(id);
			level = level+1;
		}else if($(node).hasClass(that.wrapClass)){
			var childNode = $(node).eq(id);
			level = level+1;
		}else if($(node).hasClass(that.dragClass)){
			var childNode = $(node).children().eq(id);
			level = level+1;
		}
		if(!empty(childNode)){
			that.renderControl(control, childNode, ids, level);
		}
	}
}

DRAGOBJ.addToNode = function(node, indexs, value, level){
	if( typeof(indexs)=='object' && Object.keys(indexs).length>0){
		if(indexs['parent']=='root'){
			var selector = node.getElementsByTagName('root')[0];
			if(indexs['index']==-1){
				selector.appendChild(this.typecToNode(value));
			}else if(indexs['index']==-2){
				var childNode = selector.childNodes[0];
				selector.insertBefore(this.typecToNode(value), childNode);
			}else{
				var childNode = selector.childNodes[indexs['index']];
				if(childNode){
					// node = this.insertAfter(this.typecToNode(value), childNode);
					selector.insertBefore(this.typecToNode(value), childNode);
				}else{
					selector.appendChild(this.typecToNode(value));
				}
			}
		}else{
			console.log(indexs['parent']);
			var selector = node.getElementById(indexs['parent']);
			if(indexs['index']==-1){
				selector.appendChild(this.typecToNode(value));
			}else if(indexs['index']==-2){
				var childNode = selector.childNodes[0];
				selector.insertBefore(this.typecToNode(value), childNode);
			}else{
				var childNode = selector.childNodes[indexs['index']];
				if(childNode){
					// node = this.insertAfter(this.typecToNode(value), childNode);
					selector.insertBefore(this.typecToNode(value), childNode);
				}else{
					selector.appendChild(this.typecToNode(value));
				}
			}
		}
	}
	return node;
}
DRAGOBJ.insertAfter = function (newnode,child){
	console.log(child);
    //获取目标节点的父节点
	var parent = child.parentNode;
	try{
		if(parent.lastChild == child){
		    parent.appendChid(newnode);
		}else{
		    parent.insertBefore(newnode,child.nextSibling);
		}
	}catch(e){
		console.log(parent);
	}	
}
DRAGOBJ.typecToNode = function(typec){
	var node = xmlDoc.createElement(typec['type']);
	node.setAttribute('id', typec['datas']['id']);
	node.setAttribute('data', JSON.stringify(typec['datas']));
	return node;
}
DRAGOBJ.nodeToTypec = function(node){
	var datas = JSON.parse(node.getAttribute('data'));
	console.log(datas);
	var typec = this.toControl(datas['type']);
	typec.setDatas(datas);
	return typec;
}
DRAGOBJ.deleteNode = function(obj, id){
	let result = [];
	if (obj && typeof obj === 'object') {
	    if (Array.isArray(obj)) {
	      for (let i = 0; i < obj.length; i++) {
	      	if(!Array.isArray(obj[i]) && obj[i].datas["id"]==id){
	      		obj.splice(i, 1);
	      		return obj;
	      	}else{
	      		var childs = this.deleteNode(obj[i], id);
	      		result.push(childs);
	      	}
	      }
	    } else {
    		if(!empty(obj["datas"]["childs"])){
    			var childs = this.deleteNode(obj["datas"]["childs"], id);
    			obj["datas"]["childs"] = childs;
    			return obj;
    		}
	    }
  	}
  	return result;
}

DRAGOBJ.getNode = function(id){
	let result;
	var node = this.node;
	result = node.getElementById(id);
	if(result){
		var datas = result.getAttribute('data');
		datas = JSON.parse(datas);
		result = this.toControl(result.nodeName);
		result.setDatas(datas);
		return result;
	}
  	return false;
}

DRAGOBJ.removeContorl = function(id){
	var that = this;
	that.removeContorlNode(id);
	that.control = null;
}
DRAGOBJ.removeDo = function(id){
	var that = this;
	if(!empty(id)){
		dragObj.removeContorl(id);
		var selector = $("form."+that.dragClass).find("[data-id='"+id+"']");
		if(selector.eq(0).parent().attr('web-drag')){
			selector.eq(0).parent().remove();
		}else{
			selector.eq(0).remove();
		}
	}
}
DRAGOBJ.isOldData = function(data){
	return !empty(data.datas) && !empty(data.datas["id"]) &&!empty(data.datas["id"]["value"]);
}
DRAGOBJ.getContorl = function(id){
	var that = this;
	var contorl = this.getNode(id);
	console.log(contorl);
	return contorl;
}
DRAGOBJ.getParentContorlSub = function(id){
	let result;
	var node = this.node;
	result = node.getElementById(id).parentNode;

	if(result){
		var datas = result.getAttribute('data');
		datas = JSON.parse(datas);
		let contorl = this.toControl(result.nodeName);
		if(contorl){
			contorl.setDatas(datas);
			if(!empty(datas['childs'][0])){
				datas['childs'][0] = datas['childs'][0] - 1;
				result.setAttribute('data', JSON.stringify(datas));
			}
			return contorl;			
		}
	}
  	return false;
}
DRAGOBJ.getModule = function(id){
	var that = this;
	var contorlCache = this.contorlCache;
	var contorl = this.getNode(id);
	return contorl;
}
DRAGOBJ.ChangeControl = function(typec) {
	var that = this;
	var contorl = that.node.getElementById(typec.datas['id']);
	contorl.setAttribute('data', JSON.stringify(typec.getData()));
	var sthml = this.nodeToHtml(contorl);
	var selector = $("."+that.wrapClass+"[data-id='"+typec.datas['id']+"']");
	selector.prop('outerHTML',sthml);
}
DRAGOBJ.nodeToHtml = function(node){
	var typec = this.nodeToTypec(node);
	var shtml = typec.getHtml();
	var parser = new DOMParser();
	var doc = parser.parseFromString(shtml, 'text/html');
	var newNode = doc.body.firstChild;
	if(node.childNodes.length > 0){
		for(var i=0; i<node.childNodes.length; i++ ){
			var childShtml = this.nodeToHtml(node.childNodes[i]);
			var docC = parser.parseFromString(childShtml, 'text/html');
			newNode.appendChild(docC.body.firstChild);
		}
	}
	return newNode.outerHTML;
}

window.dragObj = DRAGOBJ;


function getTextContentExcludingChildren(node) {
  if (node.nodeType === Node.TEXT_NODE) {
    return node.textContent.trim();
  }
 	console.log(node.nodeType, Node.ELEMENT_NODE);
  if (node.nodeType === Node.ELEMENT_NODE) {
    return Array.from(node.childNodes)
      .map(getTextContentExcludingChildren)
      .join('')
      .trim();
  }
  return '';
}
}(window);

var widgetHtml ={
	modal:function(id, content, settings){
		var str = '<div>';
		str += '<!-- Nav tabs -->';
		str += '  <ul class="nav nav-tabs" role="tablist">';
		str += '	<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">內容</a></li>';
		str += '	<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Style屬性</a></li>';
		str += '  </ul>';

		str += '  <!-- Tab panes -->';
		str += '  <form id="'+id+'"><div class="tab-content">';
		str += '	<div role="tabpanel" class="tab-pane active" id="home">';
		str += content;
		str += '	</div>';
		str += '	<div role="tabpanel" class="tab-pane" id="profile"><div class="form-group">';
		str += '	'+widgetHtml.textInput('class', (settings['class'] ? settings['class'] : ''), '類名')+'';
		str += '	'+widgetHtml.textInput('class_id', (settings['class_id'] ? settings['class_id'] : ''), '樣式ID')+'';
		str += '	'+widgetHtml.textInput('style', (settings['style'] ? settings['style'] : ''), '樣式style')+'';
		str += '  </div></div></div></form>';

		str += '	</div>';
		return str;
	},
	options:function(id, settings){
		var str = '<div>';
		str += '<!-- Nav tabs -->';
		str += '  <ul class="nav nav-tabs" role="tablist">';
		str += '	<li role="presentation" class="active"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Style屬性</a></li>';
		str += '  </ul>';

		str += '  <!-- Tab panes -->';
		str += '  <form id="'+id+'"><div class="tab-content">';
		str += '	<div role="tabpanel" class="tab-pane active" id="profile"><div class="form-group">';
		str += '	'+widgetHtml.textInput('class', (settings['class'] ? settings['class'] : ''), '類名')+'';
		str += '	'+widgetHtml.textInput('class_id', (settings['class_id'] ? settings['class_id'] : ''), '樣式ID')+'';
		str += '	'+widgetHtml.textInput('style', (settings['style'] ? settings['style'] : ''), '樣式style')+'';
		str += '  </div></div></div></form>';
		str += '	</div>';
		return str;
	},
	textInput:function(name,value,label){
		var str = `<div class="form-group"><label>${label ? label : ''}</label><input type="text" name="${name}" value="${value ? value : ''}" class="form-control"></div>`;
		return str;
	},
	dropDownList:function(name,value,label, items){
		var options = '<option>----</option>';
		if(items){
			for(var x in items){
				if(x==value){
					options += '<option value="'+x+'" selected>'+items[x]+'</option>';
				}else{
					options += '<option value="'+x+'">'+items[x]+'</option>';
				}
				
			}
		}
		var str = `<div class="form-group"><label>${label ? label : ''}</label><select name="${name}" class="form-control">${options}</select></div>`;
		return str;
	},
	textArea:function(name,value,label){
		var str = `<div class="form-group"><label>${label ? label : ''}</label><textarea name="${name}" class="form-control">${value ? value : ''}</textarea></div>`;
		return str;
	}
}

function WidgetObject(){
	this.name = '';
	this.type = '';
	this.icon = 'icon-duohangshurukuang';
	this.datas = {
			//控件属性
			name: '', //控件名称
			type: '',
			value:{}
		};
	this.init = function(){

	}
	this.getData = function(){
		return this.datas;
	}
	this.setData = function(values){
		this.datas.value = values;
	}
	this.setDatas = function(obj){
		this.datas = obj;
	}
	this.saveData = function(){
		var values = $("#myModal form").serializeArray();
		this.datas.value = arrayToObject(values);
	}
	this.getHtml = function() {
		var content = '';
		if(this.datas.value['content']){
			content = this.datas.value['content'];
		}
		if(empty(content) || Object.keys(content).length==0){
			content = '';
		}
		return '<div class="'+window.dragObj.wrapClass+' '+this.type+'-node" data-id="'+this.datas.id+'" data-original-title="'+this.datas.name+'" data-toggle="tooltip">'+content+'</div>';
	}
	this.render = function(){
		var id = this.datas.id;
		var content = this.inputTemplate(this.datas.id, this.datas.value);
		var str = widgetHtml.modal(this.datas.id, content, this.datas.value);
		return str;
	}
	this.inputTemplate = function(id, value){
		return '';
	}
	this.registerJs = function(){

	}
	this.close = function(){

	}
}

class ContainWidgetObject extends WidgetObject{
	constructor() {
		super(); // 调用父类构造函数
		this.render = function(){
			var str = widgetHtml.options(this.datas.id, this.datas.value);
			return str;
		}
	}
}